package cn.sh.org.service.impl;

import cn.sh.basic.service.impl.BaseServiceImpl;
import cn.sh.org.domain.Department;
import cn.sh.org.domain.Employee;
import cn.sh.org.mapper.EmployeeMapper;
import cn.sh.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService{
    @Autowired
    private EmployeeMapper employeeMapper;

    //查询所有信息
    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public Employee selectOne(Long id) {
        return employeeMapper.selectOne(id);
    }

    //添加信息
    @Override
    @Transactional
    public void add(Employee employee) {
        employeeMapper.add(employee);
        this.update(employee);
    }

   //修改信息
    @Override
    @Transactional
    public void update(Employee employee) {
      /*   if (employee.getParent()==null){
            String dirPath = "/" + employee.getId();
            employee.setDepartment_id(dirPath);
        }else {
            Long parentId = employee.getParent().getId();
            Employee parent = employeeMapper.selectOne(parentId);
            employeeMapper.setDirPath(parent.getDirPath() + "/" + employee.getId());
        }*/
        employeeMapper.update(employee);
    }

    //删除信息
    @Override
    @Transactional
    public void delete(Long id) {
        employeeMapper.delete(id);
    }

    @Override
    public List<Employee> getTree() {
        List<Employee> all = employeeMapper.selectAll();//获取所有部门
        List<Employee> result = new ArrayList<>();//声明返回的集合 里面装一级部门

        HashMap<Long, Employee> hashMap = new HashMap<>();
        for (Employee employee : all) {
            hashMap.put(employee.getId(),employee);
        }

        for (Employee temp : all) {
            if (temp.getDepartment_id() == null){//一级部门
                result.add(temp);
            }else {//非一级部门
                Long parent_id = temp.getDepartment_id();/*获取部门的父部门id*/
                Employee parent = hashMap.get(parent_id);/*根据父部门id拿到父部门对象*/
                parent.getChildren().add(temp);
            }
        }

        return result;
    }
}
